package cn.wei.sdd.core.service.impl;

import cn.wei.common.exception.Assert;
import cn.wei.common.result.ResponseEnum;
import cn.wei.sdd.core.enums.CashPaymentStatusEnum;
import cn.wei.sdd.core.enums.CheckStatusEnum;
import cn.wei.sdd.core.enums.HandleStatusEnum;
import cn.wei.sdd.core.enums.TransStatusEnum;
import cn.wei.sdd.core.mapper.*;
import cn.wei.sdd.core.pojo.entity.*;
import cn.wei.sdd.core.pojo.query.CheckRecordQuery;
import cn.wei.sdd.core.pojo.vo.AdminCheckOneVO;
import cn.wei.sdd.core.pojo.vo.CheckOrdersVO;
import cn.wei.sdd.core.service.CheckRecordService;
import cn.wei.sdd.core.service.UserService;
import cn.wei.sdd.core.utils.MyEncryptUtils;
import cn.wei.sdd.core.utils.NoUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 验收记录表 服务实现类
 * </p>
 *
 * @author Wei
 * @since 2021-11-15
 */
@Service
public class CheckRecordServiceImpl extends ServiceImpl<CheckRecordMapper, CheckRecord> implements CheckRecordService {

    @Resource
    private OrdersMapper ordersMapper;

    @Resource
    private OrderItemMapper orderItemMapper;

    @Resource
    private DictMapper dictMapper;

    @Resource
    private InWarehouseMapper inWarehouseMapper;

    @Resource
    private WarehouseProductMapper warehouseProductMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserService userService;

    @Resource
    private UserAccountMapper userAccountMapper;

    @Resource
    private TransFlowMapper transFlowMapper;

    @Override
    public List<CheckOrdersVO> getCheckOrdersByUserId(Long userId,Integer status) {
        List<CheckOrdersVO> list = baseMapper.getWaitCheckByUid(userId, status);
        for (CheckOrdersVO checkOrdersVO : list) {
            try {
                checkOrdersVO.setCheckCode(MyEncryptUtils.AESdecrypt(checkOrdersVO.getCheckCode()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    @Override
    public IPage<CheckOrdersVO> listPage(Page<CheckOrdersVO> pageParam, CheckRecordQuery checkRecordQuery) {
        if (checkRecordQuery==null){
            return baseMapper.mySelectPage(pageParam,null);
        }else {
            return baseMapper.mySelectPage(pageParam,checkRecordQuery);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void check(AdminCheckOneVO adminCheckOneVO, Long userId) {

        /**
         * 分析：
         *  1、验收成功
         *  2、物品存入仓库
         *  3、回收员更改账户余额，添加流水
         *  4、更改打包订单状态
         */
        Integer status = adminCheckOneVO.getStatus();
        String orderNo = adminCheckOneVO.getOrderNo();
        String memo = adminCheckOneVO.getMemo();
        String checkCode = adminCheckOneVO.getCheckCode();
        //验收失败
        if (status==CheckStatusEnum.CHECK_ERROR.getStatus()){
            //更改订单状态
            UpdateWrapper<CheckRecord> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("order_no",orderNo)
                    .set("status",CheckStatusEnum.CHECK_ERROR.getStatus())
                    .set("checker_id",userId)
                    .set("memo",memo);
            baseMapper.update(null,updateWrapper);

        }
        //验收成功
        if(status==CheckStatusEnum.IS_Check.getStatus()){
            QueryWrapper<CheckRecord> checkRecordQueryWrapper = new QueryWrapper<>();
            checkRecordQueryWrapper.eq("order_no",orderNo);
            CheckRecord checkRecord = baseMapper.selectOne(checkRecordQueryWrapper);

            //判断验收码是否一致
            String trueCode ="";
            try {
                trueCode = MyEncryptUtils.AESdecrypt(checkRecord.getCheckCode());
                System.out.println("");
            } catch (Exception e) {
                e.printStackTrace();
            }
            Assert.equals(trueCode,checkCode, ResponseEnum.CHECK_CODE_ERROR);

            //更改订单状态
            UpdateWrapper<CheckRecord> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("order_no",orderNo)
                    .set("status",CheckStatusEnum.IS_Check.getStatus())
                    .set("checker_id",userId)
                    .set("memo",memo);
            baseMapper.update(null,updateWrapper);



            //获取订单信息
            QueryWrapper<Orders> ordersQueryWrapper = new QueryWrapper<>();
            ordersQueryWrapper.eq("order_no",orderNo);
            Orders orders = ordersMapper.selectOne(ordersQueryWrapper);

            //更改订单表回收员处理订单状态

            UpdateWrapper<Orders> ordersUpdateWrapper = new UpdateWrapper<>();
            Orders ordersUpdateByOrderNo = new Orders();
            ordersUpdateByOrderNo.setId(orders.getId());
            ordersUpdateByOrderNo.setRecyclerStatus(HandleStatusEnum.FINISH_ORDER.getStatus());
            ordersMapper.updateById(ordersUpdateByOrderNo);


            //入库
            QueryWrapper<OrderItem> orderItemQueryWrapper = new QueryWrapper<>();
            orderItemQueryWrapper.eq("order_id",orders.getId());
            List<OrderItem> orderItems = orderItemMapper.selectList(orderItemQueryWrapper);
            String inNo = NoUtils.getInNo();
            for (OrderItem item : orderItems) {
                //添加入库记录
                String parentName = dictMapper.getParentNameByDictId(item.getDictId());
                InWarehouse inWarehouse = new InWarehouse();
                inWarehouse.setInNo(inNo);
                inWarehouse.setDictId(item.getDictId());
                inWarehouse.setInNum(item.getWeight());
                inWarehouse.setOperatorId(userId);
                inWarehouse.setParentName(parentName);
                inWarehouseMapper.insert(inWarehouse);

                //入库
                WarehouseProduct warehouseProduct = new WarehouseProduct();
                //查询当前商品库存
                QueryWrapper<WarehouseProduct> warehouseProductQueryWrapper = new QueryWrapper<>();
                warehouseProductQueryWrapper.eq("dict_id",item.getDictId());
                WarehouseProduct product = warehouseProductMapper.selectOne(warehouseProductQueryWrapper);
                //当前商品数量
                Double currentNum = item.getWeight();
                if (product!=null){
                    //加上原来数量
                    currentNum+=product.getCurrentNum();
                }
                warehouseProduct.setDictId(item.getDictId());
                warehouseProduct.setCurrentNum(currentNum);

                //如果没有当前商品，插入数据
                if (product==null){
                    warehouseProduct.setParentName(parentName);
                    warehouseProductMapper.insert(warehouseProduct);
                }else{
                    //存在更新
                    warehouseProduct.setId(product.getId());
                    warehouseProductMapper.updateById(warehouseProduct);
                }


            }

            //获取回收员用户信息
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("user_type",User.Recycler)
                    .eq("id",orders.getRecyclerId());


            User user = userMapper.selectOne(userQueryWrapper);

            //获取用户提成百分比
            BigDecimal percent = userService.getPercentByUserId(orders.getRecyclerId());
            //相乘,取百分比
            percent = percent.multiply(BigDecimal.valueOf(0.01));
            //订单总金额
            BigDecimal totalPrice = orders.getTotalPrice();
            //计算提成
            BigDecimal tiCheng = totalPrice.multiply(percent).setScale(2, BigDecimal.ROUND_HALF_UP);


            //更新用户账户
            QueryWrapper<UserAccount> userAccountQueryWrapper = new QueryWrapper<>();
            userAccountQueryWrapper.eq("user_type",User.Recycler)
                    .eq("user_id",orders.getRecyclerId());

            UserAccount userAccount = new UserAccount();
            //获取原有金额
            UserAccount account = userAccountMapper.selectOne(userAccountQueryWrapper);

            userAccount.setId(account.getId());

            //设置累计收益
            BigDecimal totalShouyi = account.getTotalShouyi();
            totalShouyi = totalShouyi.add(tiCheng);
            userAccount.setTotalShouyi(totalShouyi);


            BigDecimal amount = account.getAmount().setScale(2, BigDecimal.ROUND_HALF_UP);

            //账户余额+提成
            amount = amount.add(tiCheng);
            System.out.println("账户余额+提成:"+amount);


            //判断是否垫付,如果垫付，添加垫付流水，把垫付的钱加到账户金额
            if(orders.getCashPayment()== CashPaymentStatusEnum.IS_cashPayment.getStatus()){
                //账户余额+提成+垫付金额
                amount =amount.add(totalPrice);
                System.out.println("账户余额+提成+垫付金额:"+amount);
                //添加垫付流水
                TransFlow transFlow = new TransFlow();
                transFlow.setUserType(User.Recycler);
                transFlow.setUserId(orders.getRecyclerId());
                transFlow.setTransNo(NoUtils.getTransNo());
                transFlow.setUserName(user.getUserName());
                transFlow.setTransType(TransStatusEnum.INCOME.getStatus());
                transFlow.setTransTypeName(TransStatusEnum.INCOME.getMsg());
                transFlow.setTransAmount(orders.getTotalPrice());
                transFlow.setMemo(CashPaymentStatusEnum.IS_cashPayment.getMsg()+"，订单号："+orderNo);
                transFlowMapper.insert(transFlow);
            }
            userAccount.setAmount(amount);
            userAccountMapper.updateById(userAccount);


            //添加流水
            TransFlow transFlow = new TransFlow();
            transFlow.setUserType(User.Recycler);
            transFlow.setUserId(orders.getRecyclerId());
            transFlow.setTransNo(NoUtils.getTransNo());
            transFlow.setUserName(user.getUserName());
            transFlow.setTransType(TransStatusEnum.INCOME.getStatus());
            transFlow.setTransTypeName(TransStatusEnum.INCOME.getMsg());
            transFlow.setTransAmount(tiCheng);
            transFlow.setMemo("回收订单收入，订单号："+orderNo);
            transFlowMapper.insert(transFlow);

            //更新用户信息
            //累计回收次数
            Integer number = user.getRecoveryNumber();
            //累计回收重量
            double weight = ordersMapper.getOrdersTotalWeight(adminCheckOneVO.getOrderNo());
            double totalWeight =weight + user.getRecoveryWeight();
            UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
            userUpdateWrapper
                    .eq("id",user.getId())
                    .set("recovery_number",number+1)
                    .set("recovery_weight",totalWeight);

            userMapper.update(null,userUpdateWrapper);


        }


    }


}
